package xyz.jfshare.netty.study.server.bootstrap;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import xyz.jfshare.netty.study.server.handler.ChatServerInitializer;
import xyz.jfshare.netty.study.server.service.FriendService;
import xyz.jfshare.netty.study.server.service.MessageService;
import xyz.jfshare.netty.study.server.service.UserService;

@Component
public class ChatServer {

    @Autowired
    private UserService userService;
    @Autowired
    private FriendService friendService;
    @Autowired
    private MessageService messageService;

    public void run(String[] args) throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            //启动时设置所有用户状态为离线，防止服务器异常关闭导致用户在线无法登录
            userService.setAllOffline();
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup,workerGroup).channel(NioServerSocketChannel.class)
                    .childHandler(new ChatServerInitializer(userService,friendService,messageService));

            String port = "8899";
            if(args.length != 0){
                port = args[1];
            }

            ChannelFuture channelFuture = bootstrap.bind(Integer.parseInt(port)).sync();
            channelFuture.channel().closeFuture().sync();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
